//
//  AudioControlTableViewCell.m
//  MIDI
//
//  Created by 王禹丞 on 15/11/19.
//  Copyright © 2015年 QXSX. All rights reserved.
//

#import "AudioControlTableViewCell.h"
#import "STKAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "NSString+Hash.h"
#import "YCAudioPlayer.h"
@interface AudioControlTableViewCell()<STKAudioPlayerDelegate,STKDataSourceDelegate,AVAudioPlayerDelegate>


@property (weak, nonatomic) IBOutlet UIButton *startBtn;

@property (weak, nonatomic) IBOutlet UISlider *Slider;

@property (weak, nonatomic) IBOutlet UILabel *startLabel;

@property (weak, nonatomic) IBOutlet UILabel *endLabel;

@property (nonatomic,strong)STKAudioPlayer *audioPlayer;

@property (nonatomic,strong) AVAudioPlayer *avAudioPlayer;

@property (nonatomic,assign)BOOL isPlay;

@property (nonatomic,strong) NSTimer * timer;


@end


@implementation AudioControlTableViewCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *ID = @"AudioControlTableViewCell";
    AudioControlTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        
        cell = [[[NSBundle mainBundle] loadNibNamed:ID owner:nil options:nil]firstObject];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    return cell;
}


-(void)awakeFromNib{
    
    self.Slider.continuous = NO;   //拖动不触发
    
    self.Slider.value = 0.0;
    
    [self.Slider addTarget:self action:@selector(updateValue) forControlEvents:UIControlEventValueChanged];
    
    [self.Slider setThumbImage:[UIImage imageNamed:@"ico_audio_detai_slider"] forState: UIControlStateNormal];
    
    self.startLabel.text = [self convertTime:0.0];
    
    [_startBtn addTarget:self action:@selector(PlayerAndPause:) forControlEvents:UIControlEventTouchUpInside];

    
}


-(void)setSongModel:(GradingTestSongDetailModel *)songModel{
    
    if(songModel){
    
        _songModel = songModel;
    
        
        if (_songModel.isDownLoad) {
            
            [self playLocalMusic];
            
            return;
        }
        
        [self playMusic];
    
    
    }
    
}

- (void) playLocalMusic{

    self.audioPlayer = [YCAudioPlayer sharedYCAudioPlayer].player;
    
    self.isPlay = YES;
    
    [self.startBtn setImage:[UIImage imageNamed:@"ico_audio_detai_pause"]
                   forState:UIControlStateNormal];

    
    self.audioPlayer.delegate = self;

    
    NSURL *url = [NSURL fileURLWithPath:self.songModel.song_url];
    
    
    [self.audioPlayer playURL:url];

    [_avAudioPlayer prepareToPlay];
    
    [_avAudioPlayer play];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic) name:@"stopMusic" object:nil];


}



- (void) playMusic{
    
    self.audioPlayer = [YCAudioPlayer sharedYCAudioPlayer].player;
    
    self.isPlay = YES;
    
    [self.startBtn setImage:[UIImage imageNamed:@"ico_audio_detai_pause"]
                  forState:UIControlStateNormal];
    
    [self.audioPlayer playURL: [NSURL URLWithString:_songModel.song_url]];
    
    self.audioPlayer.delegate = self;
    
//     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic) name:@"stopMusic" object:nil];

}

//- (void)stopMusic{
//
//    [self.audioPlayer stop];
//
//}


- (NSString *)convertTime:(CGFloat)second{
    
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if (second/3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [formatter stringFromDate:d];
    
    return showtimeNew;
}


-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId{
    
    
    self.endLabel.text = [self convertTime:audioPlayer.duration];
    
    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState{
    
    self.endLabel.text = [self convertTime:audioPlayer.duration];
    
    
    self.Slider.minimumValue = 0.0;
    
    self.Slider.maximumValue = audioPlayer.duration;
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    
}

/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
    
    if(stopReason != STKAudioPlayerStopReasonUserAction){
        
        NSURL *url;
        
        if (_songModel.isDownLoad) {
            
           url = [NSURL fileURLWithPath:self.songModel.song_url];

        }else {
        
        
            url =[NSURL URLWithString:_songModel.song_url];
        }
   
        
        
        [self.audioPlayer  playURL:url];
    }

    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode{
    
    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId{
    
    
    
}


- (void)timeFireMethod{
    
    
    _startLabel.text = [self convertTime:self.
                           audioPlayer.progress];
    
    self.Slider.value = self.audioPlayer.progress;
    
}


- (void)updateValue{
    
    
    
    [self.audioPlayer seekToTime:self.Slider.value];
    
    self.startLabel.text = [self convertTime:self.
                               audioPlayer.progress];
    
}


- (void)PlayerAndPause:(id)sender
{
    
    if (self.isPlay) {
        
        [self.audioPlayer pause];
        
        [self.startBtn setImage:[UIImage imageNamed:@"ico_audio_detai_player"] forState:UIControlStateNormal];
        
        self.isPlay = NO;
        
    }else {
        
        [self.audioPlayer resume];
        
        
        
        [self.startBtn setImage:[UIImage imageNamed:@"ico_audio_detai_pause"] forState:UIControlStateNormal];
        
        self.isPlay = YES;
        
    }
}

@end
